package com.banciyuan.bcywebview.biz.main.mineinfo.mywork;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.detail.noveldetail.NovelIndexActivity;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.SeriesItem;

/**
 * Created by hy on 2016/3/7.
 */
public class MyNovelSetActivity extends BaseActivity {
    private RequestQueue mQueue;
    private ProgressbarHelper mProgressbarHelper;
    private PullToRefreshListView refreshListView;
    private ListView mListView;
    private String wp_id;
    private int page = 1;
    private boolean hasMore = true;
    private boolean loading = false;
    private List<SeriesItem> seriesItemList = new ArrayList<>();
    private MySeriesAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myworkseries_layout);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        Intent intent = getIntent();
        wp_id = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
    }

    @Override
    protected void initProgressbar() {
        View mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.myseries));
    }

    @Override
    protected void initUi() {
        refreshListView = (PullToRefreshListView) findViewById(R.id.lv);
        mListView = refreshListView.getRefreshableView();
    }

    @Override
    protected void initAction() {
        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && hasMore) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                try {
                    SeriesItem seriesItem = seriesItemList.get(position - 1);
                    if (!TextUtils.isEmpty(seriesItem.getWns_id())) {
                        Intent intent = new Intent(MyNovelSetActivity.this, NovelIndexActivity.class);
                        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, seriesItem.getWns_id());
                        startActivityForResult(intent, NovelIndexActivity.GO_NOVELINDEX);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (!loading) {
                    hasMore = true;
                    loading = true;
                    page = 1;
                    initData();
                }
            }
        });
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        paramsList.add(new BcyPair(HttpUtils.WPID, wp_id));
        HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + SpaceApi.getMyNovelSets();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject result = new JSONObject(s);
                    if (StatusCodeUtils.dealStatusCode(s, MyNovelSetActivity.this)) {
                        Gson gson = new Gson();
                        List<SeriesItem> tempList = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA),
                                new TypeToken<List<SeriesItem>>() {
                                }.getType());
                        if (tempList.size() == 0)
                            hasMore = false;
                        processData(tempList);
                        mProgressbarHelper.onSuccess();
                    } else {
                        mProgressbarHelper.onFailed();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void processData(List<SeriesItem> tempList) {
        if (page == 1) {
            seriesItemList = new ArrayList<>();
        }
        seriesItemList.addAll(tempList);
        if (null == mAdapter) {
            mAdapter = new MySeriesAdapter(this, seriesItemList);
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter.setdata(seriesItemList);
            mAdapter.notifyDataSetChanged();
        }
        refreshListView.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        loading = false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            finish();
        } else if (requestCode == NovelIndexActivity.GO_NOVELINDEX) {
            if (resultCode == ShareActivity.DELETE) {
                refreshListView.setRefreshing();
            }
        }
    }
}
